package com.lzh.redis.conf;

import at.pollux.thymeleaf.shiro.dialect.ShiroDialect;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.LinkedHashMap;
import java.util.Map;

@Configuration
public class ShiroConfig {

    /*创建shiro过滤器工厂*/
    @Bean
    public ShiroFilterFactoryBean shiroFilterFactoryBean(@Qualifier("securityManager") DefaultWebSecurityManager securityManager){
        System.out.println("shiro拦截器配置——————————————————————————————————");
        ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
        shiroFilterFactoryBean.setSecurityManager(securityManager);
        /**
         * Shiro内置过滤器，实现权限相关的拦截器
         * anon:无需认证，可以访问
         * authc:必须登录才可以访问
         * user:必须记住我才能使用
         * perms:拥有某个角色才能使用
         */

        Map<String,String> filterMap = new LinkedHashMap<>();

        //授权  /add的请求要有权限[user:add]
        filterMap.put("/add","perms[user:add]");
        filterMap.put("/update","perms[user:update]");

        //拦截
        filterMap.put("/static/**","anon");
        filterMap.put("/login","anon");
        filterMap.put("/index","anon");
        //测试redis是否能正常使用的接口 把它设为开放
        filterMap.put("/redisTest","anon");
        filterMap.put("/**","authc");

        shiroFilterFactoryBean.setFilterChainDefinitionMap(filterMap);
        //不登录自动转向的页面
        shiroFilterFactoryBean.setLoginUrl("/login");
        //登录后自动转向的页面
        shiroFilterFactoryBean.setSuccessUrl("/index");
        //未授权跳转到那个页面
        shiroFilterFactoryBean.setUnauthorizedUrl("/noauthor");
        //登出跳转到那个页面
        //shiroFilterFactoryBean.setLoginUrl("");

        return shiroFilterFactoryBean;
    }

    /**
     * 权限管理
     */
    @Bean(name = "securityManager")
    public DefaultWebSecurityManager securityManager(@Qualifier("userRealm") UserRealm userRealm){
        DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
        securityManager.setRealm(userRealm);
        System.out.println("权限管理+++++++++++++++++++++++++++");
        return securityManager;
    }

    /**
     * 创建Realm ，认证用
     * @return
     */
    @Bean(name = "userRealm")
    public UserRealm userRealm(){
        return new UserRealm();
    }

    /**
     * thymeleaf整合Shiro
     */
    @Bean
    public ShiroDialect shiroDialect(){
        return new ShiroDialect();
    }
}
